<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item
        label="会员卡号"
        prop="organName"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.organName"
          placeholder="会员卡号"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="单据日期"
        prop="operTimeStr"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-date-picker
          v-model="dataForm.operTimeStr"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="单据编号"
        prop="number"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.number"
          placeholder="单据编号"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="仓库名称"
        prop="DepotName"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-select v-model="dataForm.DepotName" placeholder="仓库名称" @visible-change="checked($event)"
          @change="change($event)">
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.depotName"
      :value="item.id"
      >
    </el-option>
  </el-select>
      </el-form-item>
      <el-form-item
        label="条码_名称(规格)(型号)(扩展信息)(单位)"
        prop="MaterialName"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          style="width: 100%"
          placeholder="请选择商品信息"
          v-model="dataForm.MaterialName"
          :suffix-icon="showTree ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
          @click.native="deptogglePanel($event)"
          size="medium"
          @input="input($event)"
        ></el-input>
        <div v-if="showTree" class="treeDiv" ref="tableList">
          <el-table
            @row-click="handleRegionNodeClick"
            ref="moviesTable"
            :data="memberList"
            border
            :cell-style="getCellStyle"
            :header-cell-style="getHeaderCellStyle"
            @cell-click="handleRegionNodeClick($event)"
          >
            <el-table-column
              v-for="(item, index) in Columns"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item
        label="库存"
        prop="Stock"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input v-model="dataForm.Stock" placeholder="库存"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="Unit">
        <el-input v-model="dataForm.Unit" placeholder="单位"></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="OperNumber">
        <el-input v-model="dataForm.OperNumber" placeholder="数量"></el-input>
      </el-form-item>
      <el-form-item label="单价" prop="UnitPrice">
        <el-input v-model="dataForm.UnitPrice" placeholder="单价"></el-input>
      </el-form-item>
      <el-form-item label="金额" prop="AllPrice">
        <el-input v-model="AllPrice" placeholder="金额"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    return {
      memberList: [], // 用户list
      showTree: false,
      selectTableId: "", //  table选中行id
      Columns: [
        {
          prop: "mBarCode",
          label: "条码",
        },
        {
          prop: "name",
          label: "名称",
        },
        {
          prop: "standard",
          label: "规格",
        },
        {
          prop: "model",
          label: "型号",
        },
        {
          prop: "unit",
          label: "单位",
        },
        {
          prop: "stock",
          label: "库存",
        },
        {
          prop: "inf",
          label: "扩展信息",
        },
      ],
      parentValue: [],
      value1: "",
      value2: "",
      value: "",
      datetime: "",
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        organName: "",
        operTimeStr: "",
        DepotName: "",
        number: "",
        MaterialName: "",
        Stock: "",
        Unit: "",
        OperNumber: "",
        UnitPrice: "",
      },
      dataRule: {
        DepotName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
        ],
        MaterialName: [
          {
            required: true,
            message: "条码_名称(规格)(型号)(扩展信息)(单位)不能为空",
            trigger: "blur",
          },
        ],
        Stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
        OperNumber: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        UnitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" },
        ],
      },
      options: [],
      value: "",
      id:null,
    };
  },
  methods: {
    change(id) {
      // console.log(id)
      this.id = id;
    },
    checked(e) {
      console.log(this.id)
      if (e) {
        this.$http({
          url: this.$http.adornUrl("/depot/findDepotByUserId"),
          method: "get",
          params: this.$http.adornParams({
          UBType: 'UserDepot',
          UBKeyId: 63,
        }),
        }).then(({ data }) => {
          // console.log(data.data);
          if (data && data.code === 0) {
            this.options = data.data;
          }
        });
      }
    },
    // 输入框改变触发的函数
    input(event){
      // console.log(this.id)
      // console.log(event)
      this.getMemberList();
      let value = event
       this.$http({
        url: this.$http.adornUrl(
          `/material/findBySelect`
        ),
        method: "get",
        params: this.$http.adornParams({
          q:event,
          page:1,
          rows:10,
          depotId:this.id,
          mpList: 'undefined%2Cundefined%2Cundefined'
        }),
      }).then(({ data }) => {
        // console.log(data.data.rows)
        this.memberList = data.data.rows;
      });
    },
    // 用户
    getMemberList() {
     this.$http({
        url: this.$http.adornUrl(
          `/material/findBySelect`
        ),
        method: "get",
        params: this.$http.adornParams({
          q:'',
          page:1,
          rows:10,
          depotId:this.id,
          mpList: 'undefined%2Cundefined%2Cundefined'
        }),
      }).then(({ data }) => {
        // console.log(data)
        this.memberList = data.data.rows;
      });
    },
    // 表格css
    getCellStyle() {
      return "text-align:center; ";
    },
    getHeaderCellStyle() {
      return "background: rgba(9, 37, 56,0.1);text-align:center; background: linear-gradient(to bottom,#ffffff 0,#eeeeee 100%);padding: 4px 5px;";
    },
    // 点击input 阻止冒泡 控制table显示隐藏
    deptogglePanel(event) {
      event || (event = window.event);
      event.stopPropagation
        ? event.stopPropagation()
        : (event.cancelBubble = true);
      this.showTree ? this.tableHide() : this.tableShow();
      this.getMemberList();
    },
    tableShow() {
      this.showTree = true;
      document.addEventListener("click", this.tableHideList, false);
    },
    tableHide() {
      this.showTree = false;
      document.addEventListener("click", this.tableHideList, false);
    },
    tableHideList(e) {
      if (this.$refs.tableList && !this.$refs.tableList.contains(e.target)) {
        this.tableHide();
      }
    },
    // 点击table节点
    handleRegionNodeClick(e) {
      // console.log(e.Id)
      var str = `${e.MaterialName}${e.expand}${e.model}${e.name}${e.standard}${e.unit}`;
      this.dataForm.MaterialName = str; // 用户名字
      this.$http({
        url: this.$http.adornUrl(`/material/findByIdWithBarCode?meId=${e.Id}`),
        method: "get",
      }).then(({ data }) => {
        // console.log(data.data);
        this.dataForm.OperNumber = 1;
        this.dataForm.UnitPrice = data.data.lowDecimal;
        //   let id = data.data.id
        //   console.log(id)
        //   this.$http({
        //   url: this.$http.adornUrl(
        //     `/findStockNumById?depotId=14&mId=${id}`
        //   ),
        //   method: "get",
        // }).then(({ data }) => {
        //   console.log(data.data);
        // });
      });
      this.showTree = false;
    },
    init(id, organName, number, operTimeStr) {
      // console.log(id, organName, number, operTimeStr);
      this.dataForm.id = id || 0;
      this.$http({
        url: this.$http.adornUrl("/sys/role/select"),
        method: "get",
        params: this.$http.adornParams(),
      })
        .then(({ data }) => {
          // console.log(data)
          this.roleList = data && data.code === 0 ? data.list : [];
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/depotItem/getDetailList`
              ),
              method: "get",
               params:this.$http.adornParams({
                headerId: this.dataForm.id,
                mpList: 'undefined%2Cundefined%2Cundefined'
              }),
            }).then(({ data }) => {
              // console.log(data.data.rows[0]);
              this.dataForm = data.data.rows[0];
              this.dataForm.id = id;
              this.dataForm.organName = organName;
              this.dataForm.number = number;
              this.$set(this.dataForm,'operTimeStr',operTimeStr);
              this.id=data.data.rows[0].DepotId
            });
          } else {
            this.$http({
              url: this.$http.adornUrl("/depotHead/buildNumber"),
              method: "get",
            }).then(({ data }) => {
              // console.log(data);
              this.dataForm.number = data.DefaultNumber;
            });
            this.dataForm.id = id;
            this.dataForm.organName = organName;
              this.$set(this.dataForm,'operTimeStr',new Date());

          }
        });
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // 有传入的参数为修改  return之后为增加
          if (this.dataForm.id) {
            // console.log(1);
            let info = `"{"Type":"出库","SubType":"零售","DefaultNumber":"LSCK00000000418","Number":"LSCK00000000418","LinkNumber":"","OperTime":"2020-11-02 10:47:11","OrganId":"","Salesman":"","AccountId":"17","ChangeAmount":30,"TotalPrice":"30.00","PayType":"现付","Remark":"","AccountMoneyList":"","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":""}"`;
            let rows = `"[{"DepotId":"14","MaterialExtendId":"7","Stock":"119.00","Unit":"个","OperNumber":"1","UnitPrice":"30","AllPrice":"30","Remark":""}]"`;
            this.$http({
              url: this.$http.adornUrl(
                `/depotHead/updateDepotHeadAndDetail?id=${this.dataForm.id}`
              ),
              method: "post",
              data: this.$http.adornData({
                info,
                rows,
              }),
            }).then((data) => {
              console.log(data);
              this.visible = false;
              // if (data && data.code === 0) {
              //   this.$message({
              //     message: "操作成功",
              //     type: "success",
              //     duration: 1500,
              //     onClose: () => {
              //       this.visible = false;
              //       this.$emit("refreshDataList");
              //     },
              //   });
              // } else {
              //   this.$message.error(data.msg);
              // }
            });
          }
           else {
            //增加
            // console.log(1);
            let info = `"{"Type":"出库","SubType":"零售","DefaultNumber":"LSCK00000000418","Number":"LSCK00000000418","LinkNumber":"","OperTime":"2020-11-02 10:47:11","OrganId":"","Salesman":"","AccountId":"17","ChangeAmount":30,"TotalPrice":"30.00","PayType":"现付","Remark":"","AccountMoneyList":"","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":""}"`;
            let rows = `"[{"DepotId":"14","MaterialExtendId":"7","Stock":"119.00","Unit":"个","OperNumber":"1","UnitPrice":"30","AllPrice":"30","Remark":""}]"`;
            this.$http({
              url: this.$http.adornUrl(
                `/depotHead/updateDepotHeadAndDetail?id=${this.dataForm.id}`
              ),
              method: "post",
              data: this.$http.adornData({
                info,
                rows,
              }),
            }).then((data) => {
              console.log(data);
              this.visible = false;
            });
          }
        }
      });
    },

  },
  computed: {
    //总价的依赖属性
    AllPrice() {
      return this.dataForm.UnitPrice * this.dataForm.OperNumber;
    },
  },
};
</script>
